const router = require('koa-router')()
const users = require('./users');
const login = require("./login");
const roles = require("./roles");
const menus = require("./menus");
const testpage = require("./testpage");
const { getToken, getJWTPayload } = require("../utils/token")

// 登录模块
router.use(login.routes())
// 用户管理模块
router.use(users.routes())
// 角色管理模块
router.use(roles.routes())
// 菜单管理模块
router.use(menus.routes())

router.use(testpage.routes())
// router.use('/users', permission('8'), users.routes())
// router.use("/roles", permission('8'), roles.routes())
// router.use("/menus", permission('8'), menus.routes())

module.exports = router

function permission(noAuth) {
    return async (ctx, next) => {
        // 判断headers中是否存在authorization
        if (ctx.headers && ctx.headers.authorization === undefined) {
            ctx.status = 401;
            ctx.body = {
                msg: "没有访问权限"
            }
        } else {
            // 若存在，验证token是否等于当前登录用户的用户名，
            // 等于的话，再判断此用户的角色表中的permission字段是否存在 ctx.url
            // 存在的话，next()，否则未授权
            try {
                let payload = getJWTPayload(ctx.headers.authorization);//解密，获取payload
                let hasAuth = payload.role && payload.role.indexOf(noAuth) !== -1;
                console.log('permission payload:', payload);
                console.log('permission auth:', noAuth, hasAuth);
                if (hasAuth) {
                    await next()
                    // 
                } else {
                    ctx.status = 403;
                    ctx.body = {
                        msg: "权限不足"
                    }
                }
            } catch (err) {
                // 捕获jwt的异常信息
                console.log("err:", err)
                ctx.status = 401;
                ctx.body = {
                    msg: err.message
                }
            }
        }
    }
}